package io.summer.auth.service;

import cn.hutool.core.util.ObjectUtil;
import io.summer.auth.entity.SysUser;
import io.summer.auth.entity.query.QSysUser;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * @author ml
 */
public class SysUserServiceImpl implements UserDetailsService {
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    SysUser user = new QSysUser().username.eq(username).findOne();
    if (ObjectUtil.isNull(user)) {
      throw new UsernameNotFoundException("user not found");
    }
    if (!user.isEnabled()) {
      throw new DisabledException("use disabled");
    } else if (!user.isAccountNonLocked()) {
      throw new LockedException("account locked");
    } else if (!user.isAccountNonExpired()) {
      throw new AccountExpiredException("account expired");
    } else if (!user.isCredentialsNonExpired()) {
      throw new CredentialsExpiredException("credentials expired");
    }
    return user;
  }
}
